package com.luoqiu.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.luoqiu.yygh.common.helper.JwtHelper;
import com.luoqiu.yygh.common.result.Result;
import com.luoqiu.yygh.user.utils.ConstantWxPropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/pai/ucenter/wx")
public class WxApiController {

    @Autowired
    private RestTemplate restTemplate;

    // 生成微信扫描的二维码
    @GetMapping(value = "/getQrParam")
    @ResponseBody
    public Result<Object> getQrParam() throws UnsupportedEncodingException {
        Map<String, Object> m = new HashMap<>();
        m.put("appid", ConstantWxPropertiesUtil.APPID);
        m.put("scope", "snsapi_login");
        String redirecturl = ConstantWxPropertiesUtil.REDIRECTURL;
        String encode = URLEncoder.encode(redirecturl, "utf-8");
        m.put("redirect_url", encode);
        m.put("state", "16816165");
        return Result.ok(m);
    }


    // 微信回调接口
    @GetMapping(value = "/callback")
    public ModelAndView callback(String code) {
        String buffer = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String url = String.format(buffer, ConstantWxPropertiesUtil.APPID, ConstantWxPropertiesUtil.APPSECRET, code);
        ResponseEntity<JSONObject> entity = restTemplate.getForEntity(url, JSONObject.class);
        JSONObject body = entity.getBody();
        assert body != null;
        String accessKey = body.getString("access_token");
        String openid = body.getString("openid");

        String infoUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?access_token=%s&openid=%s";
        url = String.format(infoUrl, accessKey, openid);
        ResponseEntity<JSONObject> userInfo = restTemplate.getForEntity(url, JSONObject.class);
        JSONObject infoBody = userInfo.getBody();
        assert infoBody != null;
        // save to db
        Map<String, String> m = new HashMap<>();
        m.put("name", "username");
        m.put("token", JwtHelper.createToken(1L, "username"));
        ModelAndView view = new ModelAndView("index");
        view.addObject("info", m);
        return view;
    }
}
